package com.cans.service.pms.impl;


import com.cans.dao.pms.api.ISysUserDao;
import com.cans.model.pms.SysUser;
import com.cans.security.browser.service.api.ICustomUserService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: cans
 * @Date: 2017/10/4
 * @Description:
 */
@Service("customUserService")
public class CustomUserService implements ICustomUserService {

    @Resource
    private ISysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return findByUsername(username);
    }

    @Override
    public void checkAndSave(String username) {
        SysUser findUser = findByUsername(username);
        if(findUser == null){
            SysUser user = new SysUser();
            user.setUserName(username);
            sysUserDao.save(user);
        }

    }

    private SysUser findByUsername(String username) {
        SysUser user = new SysUser();
        user.setUserName(username);
        //创建匹配器，即如何使用查询条件
        //构建对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                //姓名采用“开始匹配”的方式查询
                .withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.storeDefaultMatching());

        //创建实例
        Example<SysUser> ex = Example.of(user, matcher);

        return sysUserDao.findOne(ex);
    }
}
